using B.S.Base.Read.API.Application.Command;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System;
using WEBAPI.Damoin;
using WEBAPI.ErroeCode;
using WEBAPI.Indaseture;
using WEBAPI.Indaseture.Infasetures;
using WEBAPI.Indaseture.Inmoment;

namespace B.S.Base.Read.API.Application.CommandHandLer
{
    public class GetLeaveReportDynamicCommandHandLer : IRequestHandler<GetLeaveReportDynamicCommand, APIResult<List<LeaveSummaryDto>>>
    {
        private readonly MyDbContext _db;
        private readonly IBaseRepostiy<AccountModel> _accountmodel;
        private readonly IBaseRepostiy<ApproveModel> _approveModel;
        public GetLeaveReportDynamicCommandHandLer(MyDbContext db, IBaseRepostiy<AccountModel> accountmodel, IBaseRepostiy<ApproveModel> approveModel)
        {
            this._db = db;
            this._accountmodel = accountmodel;
            this._approveModel = approveModel;
        }

        public Task<APIResult<List<LeaveSummaryDto>>> Handle(GetLeaveReportDynamicCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<LeaveSummaryDto>> res = new APIResult<List<LeaveSummaryDto>>();
            var users =  _db.account.ToList();
            //2����ʼ����������
            var summaryList = new List<LeaveSummaryDto>();
            foreach (var user in users)
            {
                //��ѯ�û���ָ����ݵ�������ټ�¼
                var summary = new LeaveSummaryDto
                {
                    UserId = user.AccountId,
                    UserName = user.AccountName,
                    MonthlyHours = new List<int>(new int[12])//12���£���ʼ��Ϊ0
                };
                var leaveRecords =  _db.approve
                    .Where(o => o.AccountName == user.AccountName && o.StartTime.Year == request.Year)
                    .ToList();
                //ͳ��ÿ���µ���ٹ�ʱ
                foreach (var record in leaveRecords)
                {
                    int month = record.StartTime.Month - 1;
                    summary.MonthlyHours[month] += record.Number;
                }
                summaryList.Add(summary);
            }
            res.Data= summaryList;
            res.Code=ResultCode.Ok;
            res.Message = "��ʾ�ɹ�";
            return Task.FromResult(res);
        }
    }
}